package com.bsoft.gol.hcs.common.service.impl;

import com.bsoft.gol.hcs.clinical.bean.qo.DepartmentListQo;
import com.bsoft.gol.hcs.clinical.bean.qo.DoctorListQo;
import com.bsoft.gol.hcs.clinical.bean.qo.QueryOrderRecordListQo;
import com.bsoft.gol.hcs.clinical.bean.req.GetHistoricalPatientListReq;
import com.bsoft.gol.hcs.clinical.bean.vo.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.bsoft.gol.hcs.common.dao.SysParameterDAO;
import com.bsoft.gol.hcs.common.service.BaseDataService;
import ctd.controller.exception.ControllerException;
import ctd.spring.boot.annotation.SsdevReference;
import ctd.util.AppContextHolder;
import ctd.util.JSONUtils;
import com.bsoft.gol.hcs.common.bean.request.ParamsQo;
import com.bsoft.gol.hcs.enumcase.InterfaceTypeEnum;
import hcn.util.BaseResponse;
import hcn.service.commonClinical.ICommonClinicalService;
import hcn.service.commonClinical.qo.ParamsOrgQo;
import hcn.service.commonClinical.qo.QueryDoctorListRequest;
import hcn.util.ResultCode;
import lombok.extern.slf4j.Slf4j;
import opensource.jpinyin.PinyinHelper;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.atag.util.http.KdHttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import com.bsoft.gol.hcs.satisfaction.bean.vo.DictionaryVo;
import com.bsoft.gol.hcs.utils.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by ChenJij on 2020/7/21.
 */
@Service
@Slf4j
public class BaseDataServiceImpl implements BaseDataService {
    private final static Logger logger = LoggerFactory.getLogger(BaseDataServiceImpl.class);
    @Autowired
    SysParameterDAO sysParameterDAO;

    @SsdevReference("hcn.commonClinicalService")
    private ICommonClinicalService commonClinicalService;

    @Value("${project_source}")
    private String projectSource;

    @Override
    public BaseResponse<List<DepartmentListVo>> queryDepartmentList(DepartmentListQo request) {
        BaseResponse result = new BaseResponse<>();
        List<DepartmentListVo> departmentListVos = null;
        try {
            if (Constants.HOL.equals(projectSource)) {
                logger.info("进入互联网医院");
                departmentListVos = sysParameterDAO.queryDepartmentList(request);
                if (CollectionUtils.isEmpty(departmentListVos)) {
                    BaseRespUtil.setResultSuccess(new ArrayList<>());
                }
                List<String> deptIdList = new ArrayList<>();
                for (DepartmentListVo departmentListVo : departmentListVos) {
                    deptIdList.add(departmentListVo.getDepartmentId());
                }
                List<DepartmentListVo.DepartmentListBean> departmentSunList = sysParameterDAO.querySunDepartmentList(request.getOrganizationId(), deptIdList);
                for (DepartmentListVo.DepartmentListBean departmentListBean : departmentSunList) {
                    for (DepartmentListVo departmentListVo : departmentListVos) {
                        if (departmentListVo.getDepartmentId().equals(departmentListBean.getpCode())) {
                            departmentListVo.getDepartmentList().add(departmentListBean);
                        }
                    }
                }
                BaseRespUtil.setResultSuccess(departmentListVos);
            } else {
                logger.info("进入智慧健康通");

                logger.info(System.getProperty("java.class.path") + "");
                String url = Constants.GOL_FAMILY_URL + Constants.GET_HCN_DEPT_LIST;
                logger.info("url:{}", url);
                String str = null;
                try {
                    str = KdHttpClientUtil.doPostJSONRequest(url, JSONUtils.writeValueAsString(request));
                } catch (Exception e) {
                    logger.info("连接失败", e);
                    result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
                    result.setCode(Constants.ERR_CODE);
                }


                if (CommonUtils.isNotEmpty(str)) {
                    JSONObject jsonObject = JSONObject.parseObject(str);
                    logger.info("str:{}", str);
                    logger.info("jsonObject:{}", jsonObject.toJSONString());
                    try {
                        if (CommonUtils.isNotEmpty(jsonObject)) {
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            if (CommonUtils.isNotEmpty(jsonArray)) {
                                departmentListVos = JSONObject.parseArray(jsonArray.toString(), DepartmentListVo.class);
                                result.setData(departmentListVos);
                                result.setCode(ResultCode.SUCCESS);
                            }
                        } else {
                            result.setCode(ResultCode.ERROR);
                            result.setMessage("获取科室列表失败");
                        }
                    } catch (JSONException e) {
                        logger.info("json转换失败", e);
                        result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
                        result.setCode(Constants.ERR_CODE);
                    }
                    logger.info("queryDepartmentList:{}", result);
                    return result;
                }
            }
            if (CommonUtils.isNotEmpty(departmentListVos)) {
                result.setData(departmentListVos);
                result.setCode(ResultCode.SUCCESS);
            }
        } catch (Exception e) {
            result.setMessage("获取科室列表失败" + e.getMessage());
            result.setCode(ResultCode.ERROR);
        }
        return result;
    }

    @Override
    public BaseResponse<List<DoctorListVo>> queryDoctorList(DoctorListQo request) {
        BaseResponse result = new BaseResponse<>();
        List<DoctorListVo> doctorListVos = null;
        try {
            if (Constants.HOL.equals(projectSource)) {
                logger.info("进入互联网医院");
                if (StringUtils.isEmpty(request.getQueryType())) {
                    request.setQueryType(1);
                }
                String url = Constants.HOL_FAMILY_URL + Constants.GET_HOL_DOCTOR_LIST;
                logger.info("url:{}", url + ",request:" + request.toString());
                String str = KdHttpClientUtil.doPostJSONRequest(url, JSONUtils.writeValueAsString(request));
                logger.info("str:{}", str);
                JSONObject jsonObject = JSONObject.parseObject(str);
                if (CommonUtils.isNotEmpty(jsonObject)) {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    if (CommonUtils.isNotEmpty(jsonArray)) {
                        doctorListVos = JSONObject.parseArray(jsonArray.toString(), DoctorListVo.class);
                        result.setData(doctorListVos);
                        result.setCode(ResultCode.SUCCESS);
                    }
                } else {
                    result.setCode(ResultCode.ERROR);
                    result.setMessage("获取医生列表失败");
                }
                return result;

//                doctorListVos = sysParameterDAO.queryDoctorList(request);
            } else {
                logger.info("进入智慧健康通");
                logger.info(System.getProperty("java.class.path") + "");
                //20210928 rpc改造
                List<DoctorListVo> list = rpcGetHcnDoctorList(request);
                if (CollectionUtils.isEmpty(list)) {
                    result.setCode(ResultCode.ERROR);
                    result.setMessage("获取医生列表失败");
                } else {
                    result.setCode(ResultCode.SUCCESS);
                    result.setData(list);
                }
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("获取医生列表失败");
            result.setCode(ResultCode.ERROR);
        }
        return result;
    }

    /**
     * rpc获取健康通医生列表
     */
    private List<DoctorListVo> rpcGetHcnDoctorList(DoctorListQo request) {
        try {
            log.info("rpc获取健康通医生列表-{}", ReflectionToStringBuilder.toString(request));
            QueryDoctorListRequest q = new QueryDoctorListRequest();
            BeanUtils.copyProperties(request, q);
            List<Map<String, Object>> result = commonClinicalService.queryDoctorList(q);
            if (!CollectionUtils.isEmpty(result)) {
                ObjectMapper mapper = new ObjectMapper();
                mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                return result.stream().map(m -> mapper.convertValue(m, DoctorListVo.class)).collect(Collectors.toList());
            }
        } catch (Exception e) {
            log.error("rpc获取健康通医生列表失败", e);
        }
        return Collections.emptyList();
    }


    /**
     * 智慧健康通专用
     *
     * @param request
     * @return
     */
    @Override
    public BaseResponse<List<DoctorInfo>> queryDoctorUserIdList(DoctorListQo request) {
        BaseResponse result = new BaseResponse<>();
        List<DoctorInfo> doctorListVos = null;
        logger.info("进入智慧健康通");
        logger.info(System.getProperty("java.class.path") + "");
        String url = Constants.GOL_FAMILY_URL + Constants.GET_HCN_DOCTOR_USERID_LIST;
        logger.info("url:{}", url);
        String str = null;
        try {
            str = KdHttpClientUtil.doPostJSONRequest(url, JSONUtils.writeValueAsString(request));
            ;
        } catch (Exception e) {
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(Constants.ERR_CODE);
        }

        if (CommonUtils.isNotEmpty(str)) {
            JSONObject jsonObject = JSONObject.parseObject(str);
            logger.info("str:{}", str);
            logger.info("jsonObject:{}", jsonObject.toJSONString());
            try {
                if (CommonUtils.isNotEmpty(jsonObject)) {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    if (CommonUtils.isNotEmpty(jsonArray)) {
                        doctorListVos = JSONObject.parseArray(jsonArray.toString(), DoctorInfo.class);
                        result.setData(doctorListVos);
                        result.setCode(ResultCode.SUCCESS);
                    }
                } else {
                    result.setCode(ResultCode.ERROR);
                    result.setMessage("获取医生列表失败");
                }
            } catch (JSONException e) {
                e.printStackTrace();
                result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
                result.setCode(Constants.ERR_CODE);
            }

            logger.info("queryDoctorList:{}", result);
            return result;
        }
        return result;
    }

    /**
     * @description: 查询健康通的机构列表信息
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/10/29 15:05
     */
    @Override
    public Map getGOLOrgParams(String organizationId) {
        ParamsOrgQo qo = new ParamsOrgQo();
        qo.setOrganizationId(organizationId);
        List<Map> maps = (List<Map>) queryOrganizationList(qo).getData();
        if (CommonUtils.isNotEmpty(maps)) {
            for (Map map : maps) {
                if (Constants.GOL.equals(projectSource)) {
                    return map;
                }
            }
        }
        return null;
    }

    /**
     * rpc 获取组织列表
     */
    private List<Map<String, Object>> rpcGetOrgList(ParamsOrgQo request) {
        try {
            log.info("rpc查询组织列表, 参数:{}", ReflectionToStringBuilder.toString(request));
            List<Map<String, Object>> result = commonClinicalService.queryOrganizationList(request);
            return result;
        } catch (Exception e) {
            log.error("rpc查询组织列表失败", e);
        }
        return null;
    }


    @Override
    public BaseResponse queryOrganizationList(ParamsOrgQo request) {
        /**  organizationId 传值是通过localOrgId获取机构信息
         *  medicalTechnologyOrganizationId  传值是通medicalTechnologyOrgCode获取机构信息
         **/
        BaseResponse result = new BaseResponse();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        String url = "";
        if (Constants.HOL.equals(projectSource)) {
            logger.info("进入互联网医院");
            jsonParams.remove("outpatientType");
            jsonParams.remove("organizationId");
            jsonParams.put("title", jsonParams.remove("organizationName"));
            jsonParams.remove("type");
//            jsonParams.remove("title");
//            jsonParams.remove("region");
            if (CommonUtils.isEmpty(request.getPageNo())) {
                jsonParams.put("pageNo", 1);
            }
            if (CommonUtils.isEmpty(request.getPageSize())) {
                jsonParams.put("pageSize", 998);
            }
            jsonParams.put("flag", 1);
            url = Constants.HOL_WEB_URL + Constants.HOL_LIST_ORGANATION;
        } else {
            logger.info("进入智慧健康通");
//            url = Constants.GOL_FAMILY_URL + Constants.GOL_LIST_ORGANATION;
            //20210928 rpc 改造
            List<Map<String, Object>> list = rpcGetOrgList(request);
            if (!CollectionUtils.isEmpty(list)) {
                result.setCode(ResultCode.SUCCESS);
                result.setData(list);
                return result;
            }
            result.setMessage("获取机构列表失败");
            result.setCode(ResultCode.ERROR);
            return result;
        }

        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS) {
                if (Constants.HOL.equals(projectSource)) {
                    List<Map> maps = new ArrayList<>();
                    JSONObject data = (JSONObject) jsonObject.get("data");
                    JSONArray list = (JSONArray) data.get("list");
                    for (int i = 0; i < list.size(); i++) {
                        Map map = new HashMap(4);
                        JSONObject jb = list.getJSONObject(i);
                        map.put("organizationId", jb.get("code"));
                        map.put("organizationName", jb.get("title"));
                        map.put("medicalTechnologyOrganizationId", jb.get("medicalTechnologyOrgCode"));
                        map.put("localDoctorId", request.getDocId());
                        map.put("navigationUrl", jb.get("navigationUrl"));
                        maps.add(map);
                    }
                    result.setData(maps);
                } else {
                    result.setData(jsonObject.get("data"));
                }
                result.setCode(ResultCode.SUCCESS);
            } else {
                result.setCode(ResultCode.ERROR);
                result.setMessage("获取机构列表");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("获取机构列表失败");
            result.setCode(ResultCode.ERROR);
        }
        return result;
    }

    /**
     * @description: 通过医技机构代码查询机构信息
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/12/11 13:43
     * @param: medicalTechnologyOrganizationId
     * @return: java.util.Map
     */
    @Override
    public Map getOrgInfoByMedicalId(String medicalTechnologyOrganizationId) {
        ParamsOrgQo qo = new ParamsOrgQo();
        qo.setMedicalTechnologyOrganizationId(medicalTechnologyOrganizationId);
        List<Map> maps = (List<Map>) queryOrganizationList(qo).getData();
        if (CommonUtils.isNotEmpty(maps)) {
            return maps.get(0);
        }
        return null;
    }


    @Override
    public BaseResponse questionList(EditorQuestionQo request) {
        BaseResponse result = new BaseResponse();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        List<QuestionVo> res = null;
        String url = Constants.EDITOR_FOLLOW_UP + Constants.GET_QUESTIONNAIRE_LIST;
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
        logger.info("{}返回值json:{}", "", jsonObject.toJSONString());
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null && !jsonObject.getJSONObject("data").isEmpty()) {
              /*  res = JSONObject.parseArray(
                        jsonObject.get("data").toString(), QuestionVo.class);*/

                result.setData(JSONObject.parse(Utils.Html2Text(jsonObject.get("data").toString())));

                result.setCode(ResultCode.SUCCESS);
            } else {
                result.setCode(ResultCode.ERROR);
                result.setMessage("获取编辑器信息失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(Constants.ERR_CODE);
        }

        return result;
    }

    @Override
    public BaseResponse questionTitleList(EditorQuestionQo request) {
        BaseResponse result = new BaseResponse();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        String url = Constants.EDITOR_FOLLOW_UP + Constants.GET_QUESTIONNAIRE_TITLE_LIST;
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
        logger.info("{}返回值json:{}", "", jsonObject.toJSONString());
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null && !jsonObject.getJSONObject("data").isEmpty()) {
                Map<String, Object> res = JSONObject.parseObject(jsonObject.get("data").toString());

                if (null != res) {
                    List<Map<String, Object>> list = (List<Map<String, Object>>) res.get("list");
                    if (CommonUtils.isNotEmpty(list)) {
                        List<Map<String, Object>> questionVos = new ArrayList<>();
                        for (Map<String, Object> objectMap : list) {
                            String widgetType = String.valueOf(objectMap.get("widgetType"));
                            //只返回前六种类型  1单选题、2多选题、3下拉选、4字典选、5级联选择、6单项填空
                            if ("1".equals(widgetType) || "2".equals(widgetType)
                                    || "3".equals(widgetType) || "4".equals(widgetType)
                                    || "5".equals(widgetType) || "6".equals(widgetType)) {
                                questionVos.add(objectMap);
                            }
                        }
                        res.put("total", questionVos.size());
                        res.put("list", questionVos);
                        result.setData(JSONObject.parse(Utils.Html2Text(JSONUtils.writeValueAsString(res))));
                    }
                }
                result.setCode(ResultCode.SUCCESS);
            } else {
                result.setCode(ResultCode.ERROR);
                result.setMessage("获取编辑器信息失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(Constants.ERR_CODE);
        }

        return result;
    }

    @Override
    public BaseResponse questionAnswerList(EditorQuestionQo request) {
        BaseResponse result = new BaseResponse();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        List<QuestionVo> res = null;
        String url = Constants.EDITOR_FOLLOW_UP + Constants.GET_QUESTIONNAIRE_ANSWER_LIST;
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
        logger.info("{}返回值json:{}", "", jsonObject.toJSONString());
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null && !jsonObject.getJSONObject("data").isEmpty()) {
              /*  res = JSONObject.parseArray(
                        jsonObject.get("data").toString(), QuestionVo.class);*/

                result.setData(JSONObject.parse(Utils.Html2Text(jsonObject.get("data").toString())));

                result.setCode(ResultCode.SUCCESS);
            } else {
                result.setCode(ResultCode.ERROR);
                result.setMessage("获取编辑器信息失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(Constants.ERR_CODE);
        }
        return result;
    }

    @Override
    public BaseResponse questionTitleOptionList(EditorQuestionQo request) {
        BaseResponse result = new BaseResponse();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        List<QuestionVo> res = null;
        String url = Constants.EDITOR_FOLLOW_UP + Constants.GET_QUESTIONNAIRE_OPTION_LIST;
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
        logger.info("{}返回值json:{}", "", jsonObject.toJSONString());
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null && !jsonObject.getJSONObject("data").isEmpty()) {
              /*  res = JSONObject.parseArray(
                        jsonObject.get("data").toString(), QuestionVo.class);*/

                result.setData(JSONObject.parse(Utils.Html2Text(jsonObject.get("data").toString())));

                result.setCode(ResultCode.SUCCESS);
            } else {
                result.setCode(ResultCode.ERROR);
                result.setMessage("获取编辑器信息失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(Constants.ERR_CODE);
        }
        return result;
    }

    @Override
    public BaseResponse questionCascadeAnswerList(EditorQuestionQo request) {
        BaseResponse result = new BaseResponse();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        List<QuestionTitleCascadeVo> res = null;
        String url = Constants.EDITOR_FOLLOW_UP + Constants.GET_QUESTIONNAIRE_OPTION_LIST;
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
        logger.info("{}返回值json:{}", "", jsonObject.toJSONString());
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null && !jsonObject.getJSONObject("data").isEmpty()) {
                JSONObject object = (JSONObject) jsonObject.get("data");
                if (object.get("list") != null) {
                    res = JSONObject.parseArray(
                            object.get("list").toString(), QuestionTitleCascadeVo.class);

                    List<QuestionTitleCascadeVo> cascadeVos = buidTree(res);
                    result.setData(cascadeVos);
                }

//                result.setData(JSONObject.parse(Utils.Html2Text(jsonObject.get("data").toString())));
                result.setCode(ResultCode.SUCCESS);
            } else {
                result.setCode(ResultCode.ERROR);
                result.setMessage("获取编辑器信息失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(Constants.ERR_CODE);
        }
        return result;
    }

    static List<QuestionTitleCascadeVo> buidTree(List<QuestionTitleCascadeVo> list) {
        List<QuestionTitleCascadeVo> tree = new ArrayList<QuestionTitleCascadeVo>();
        for (QuestionTitleCascadeVo vo : list) {
            if ("0".equals(vo.getPid())) {
                tree.add(findChild(vo, list));
            }
        }
        return tree;
    }

    static QuestionTitleCascadeVo findChild(QuestionTitleCascadeVo vo, List<QuestionTitleCascadeVo> list) {
        for (QuestionTitleCascadeVo n : list) {
            if (n.getPid().equals(vo.getOptionId())) {
                if (vo.getChildren() == null) {
                    vo.setChildren(new ArrayList<QuestionTitleCascadeVo>());
                }
                vo.getChildren().add(findChild(n, list));
            }
        }
        return vo;
    }

    @Override
    public BaseResponse questionDetail(EditorQuestionQo request) {
        BaseResponse result = new BaseResponse();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        QuestionVo res = null;
        String url = Constants.EDITOR_FOLLOW_UP + Constants.GET_QUESTION_DETAIL;
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
        logger.info("{}返回值json:{}", "", jsonObject.toJSONString());
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null && !jsonObject.getJSONObject("data").isEmpty()) {
              /*  res = JSONObject.parseArray(
                        jsonObject.get("data").toString(), QuestionVo.class);*/

                result.setData(JSONObject.parse(Utils.Html2Text(jsonObject.get("data").toString())));

                result.setCode(ResultCode.SUCCESS);
            } else {
                result.setCode(ResultCode.ERROR);
                result.setMessage("获取编辑器信息失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(Constants.ERR_CODE);
        }
        return result;
    }


    //提取医生列表字典
    public List<DictionaryVo> getDoctorList(String organizationId, String departmentId, String pinyinCode, Integer pageNo, Integer pageSize) {
        List<DictionaryVo> dictionaryVos = new ArrayList<>();
        DoctorListQo doctorListQo = new DoctorListQo();
        doctorListQo.setOrganizationId(organizationId);
        doctorListQo.setDepartmentId(departmentId);
        doctorListQo.setType(projectSource);
        BaseResponse<List<DoctorListVo>> baseResponse = this.queryDoctorList(doctorListQo);
        List<DoctorListVo> doctorListVos = baseResponse.getData();
        if (CommonUtils.isNotEmpty(doctorListVos)) {
            for (DoctorListVo doctorListVo : doctorListVos) {
                DictionaryVo dictionaryVo = new DictionaryVo();
                dictionaryVo.setDicCode(doctorListVo.getDoctorId());
                dictionaryVo.setDicName(doctorListVo.getDoctorName());
                //拼音码过滤
                if (CommonUtils.isNotEmpty(pinyinCode) && CommonUtils.isNotEmpty(dictionaryVo.getDicName())) {
                    String code = PinyinHelper.getShortPinyin(dictionaryVo.getDicName());
                    if (CommonUtils.isNotEmpty(code)) {
                        if (pinyinCode.toLowerCase().equals(code.toLowerCase()) || pinyinCode.equals(dictionaryVo.getDicName())) {
                            dictionaryVos.add(dictionaryVo);
                        }
                    }
                } else {
                    dictionaryVos.add(dictionaryVo);
                }
            }
        }

        //分页返回
        if (CommonUtils.isNotEmpty(dictionaryVos)) {
            Integer startPage = pageSize * pageNo - pageSize < 0 ? 0 : pageSize * pageNo - pageSize;
            Integer size = dictionaryVos.size();//记录数
            Integer endPage = pageNo * pageSize > size ? size : pageNo * pageSize;
            if (startPage.intValue() > size) {
                return null;
            }
            List<DictionaryVo> pageList = dictionaryVos.subList(startPage, endPage);
            return pageList;
        }

        return dictionaryVos;
    }

    //提取机构列表字典
    public List<DictionaryVo> getOrgList(String pinyinCode, Integer pageNo, Integer pageSize) {
        List<DictionaryVo> dictionaryVos = new ArrayList<>();
        ParamsOrgQo paramsOrgQo = new ParamsOrgQo();
        paramsOrgQo.setType(projectSource);
        BaseResponse<List<Map>> baseResponse = this.queryOrganizationList(paramsOrgQo);
        List<Map> mapList = baseResponse.getData();
        if (CommonUtils.isNotEmpty(mapList)) {
            for (Map map : mapList) {
                DictionaryVo dictionaryVo = new DictionaryVo();
                dictionaryVo.setDicCode(map.get("organizationId").toString());
                dictionaryVo.setDicName(map.get("organizationName").toString());
                //拼音码过滤
                if (CommonUtils.isNotEmpty(pinyinCode) && CommonUtils.isNotEmpty(dictionaryVo.getDicName())) {
                    String code = PinyinHelper.getShortPinyin(dictionaryVo.getDicName());
                    if (CommonUtils.isNotEmpty(code)) {
                        if (pinyinCode.toLowerCase().equals(code.toLowerCase()) || pinyinCode.equals(dictionaryVo.getDicName())) {
                            dictionaryVos.add(dictionaryVo);
                        }
                    }
                } else {
                    dictionaryVos.add(dictionaryVo);
                }
            }
        }

        //分页返回
        if (CommonUtils.isNotEmpty(dictionaryVos)) {
            Integer startPage = pageSize * pageNo - pageSize < 0 ? 0 : pageSize * pageNo - pageSize;
            Integer size = dictionaryVos.size();//记录数
            Integer endPage = pageNo * pageSize > size ? size : pageNo * pageSize;
            if (startPage.intValue() > size) {
                return null;
            }
            List<DictionaryVo> pageList = dictionaryVos.subList(startPage, endPage);
            return pageList;
        }
        return dictionaryVos;
    }

    //医生端接诊记录
    @Override
    public List<Map<String, Object>> queryGOLOrderRecordList(QueryOrderRecordListQo qo){

        List<Map<String, Object>> list = Lists.newArrayList();
        List<ConsultAskEXVo> consultAskVoList =new ArrayList<>();
        try {
            JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(qo));
            JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(Constants.GOL_FAMILY_URL
                    + Constants.QUERYORDERRECORDLIST, jsonParams);
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null) {
                //出参转换开始
                consultAskVoList= JSONObject.parseArray(
                        jsonObject.getJSONArray("data").toJSONString(), ConsultAskEXVo.class);
            }else {
                logger.error("QueryGOLOrderRecordList执行异常，原因:"+jsonObject.getString("message"));
                try {
                    throw new ControllerException(ResultCode.ERROR,jsonObject.getString("message"));
                } catch (ControllerException e) {
                    e.printStackTrace();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            logger.error("QueryGOLOrderRecordList执行异常，原因:"+e.getMessage());
            try {
                throw new ControllerException(ResultCode.ERROR,e.getMessage());
            } catch (ControllerException e1) {
                e1.printStackTrace();
            }
        }
        if (CommonUtils.isEmpty(consultAskVoList)) {
            return list;
        }
        //ui展示原因，需要每一天组一个集合
        Map<String, List<ConsultAskEXVo>> listMap = new TreeMap(
                new Comparator<String>() {
                    @Override
                    public int compare(String obj1, String obj2) {
                        // 降序排序
                        return obj2.compareTo(obj1);
                    }
                });

        for (ConsultAskEXVo consultAskVo : consultAskVoList) {
            String appointmentDate = DateUtil.formDate(consultAskVo.getAppointmentDate(), "yyyy-MM-dd");
            List<ConsultAskEXVo> dateList = listMap.get(appointmentDate);
            if (CommonUtils.isEmpty(dateList)) {
                List<ConsultAskEXVo> dateConsultAskList = Lists.newArrayList();
                dateConsultAskList.add(consultAskVo);
                listMap.put(appointmentDate, dateConsultAskList);
            } else {
                dateList.add(consultAskVo);
            }
        }

        for (Map.Entry entry : listMap.entrySet()) {
            Map map = Maps.newHashMap();
            map.put("appointmentDate",entry.getKey());
            map.put("list",entry.getValue());
            list.add(map);
        }
        return list;
    }


    /* *
 * @Describe: 获取互联网医院历史患者列表
 * @Param: [qo]
 * @Return: java.util.Map<java.lang.String,java.lang.Object>
 * @Author: zhengcb10708
 * @Date: 2021/4/20 14:59
 *
 **/
    @Override
    public Map<String, Object> getHOLHistoricalPatientList(QueryOrderRecordListQo qo){

        Map<String, Object>  result=new HashMap<>();
        GetHistoricalPatientListReq req=new GetHistoricalPatientListReq();
        req.setConsultStatus(qo.getConsultStatus());
        req.setDoctorCode(qo.getDoctorId());
        req.setBusType(qo.getConsultType());
        req.setWorkDateStart(qo.getBeginDate());
        req.setWorkDateEnd(qo.getEndDate());
        req.setPageNo(qo.getPageNo());
        req.setPageSize(qo.getPageSize());
        try {
            JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(req));
            JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(Constants.HOL_WEB_URL
                    + Constants.GETHISTORICALPATIENTLIST, jsonParams);
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null) {
                //出参转换开始
                //循环转换
                JSONObject data = JSONObject.parseObject(jsonObject.get("data").toString());
                Iterator it =data.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
                    result.put(entry.getKey(), entry.getValue());
                }
            }else {
                logger.error("getHOLHistoricalPatientList执行异常，原因:"+jsonObject.getString("message"));
                try {
                    throw new ControllerException(ResultCode.ERROR,jsonObject.getString("message"));
                } catch (ControllerException e) {
                    e.printStackTrace();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            logger.error("getHOLHistoricalPatientList执行异常，原因:"+e.getMessage());
            try {
                throw new ControllerException(ResultCode.ERROR,e.getMessage());
            } catch (ControllerException e1) {
                e1.printStackTrace();
            }
        }
        return result;
    }

    @Override
    public BaseResponse<List<Map>> findOrgList(ParamsQo paramsVo) {
        BaseResponse<List<Map>> baseResponse = new BaseResponse<>();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(paramsVo));
        String url = "";

        if (InterfaceTypeEnum.HOL.getCode().equals(paramsVo.getType())){
            log.info("进入互联网医院，查询机构列表");
            url= Constants.HOL_WEB_URL + Constants.HOL_LIST_ORGANATION;
            jsonParams = new JSONObject();
            jsonParams.put("pageNo",1);
            jsonParams.put("pageSize",999);
            JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
            try {
                if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                        jsonObject.get("data") != null) {
                    Map map = JSONObject.parseObject(
                            jsonObject.get("data").toString(), Map.class);
                    if (CommonUtils.isNotEmpty(map)) {
                        List<Map> responseList = JSONObject.parseArray(
                                map.get("list").toString(), Map.class);
                        baseResponse.setData(responseList);
                        baseResponse.setCode(ResultCode.SUCCESS);
                    }
                } else {
                    baseResponse.setCode(ResultCode.ERROR);
                    baseResponse.setMessage("获取机构列表");
                }
            } catch (Exception e) {
                e.printStackTrace();
                baseResponse.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
                baseResponse.setCode(Constants.ERR_CODE);
            }
            return baseResponse;
        }else{
            log.info("进入健康通，查询机构列表");
            url= Constants.GOL_FAMILY_URL + Constants.LIST_ORGANATION;
            JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
            try {
                if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                        jsonObject.get("data") != null) {
                    List<Map> responseList = new ArrayList<>();
                    responseList = JSONObject.parseArray(
                            jsonObject.get("data").toString(), Map.class);
                    baseResponse.setData(responseList);
                    baseResponse.setCode(ResultCode.SUCCESS);
                } else {
                    baseResponse.setCode(ResultCode.ERROR);
                    baseResponse.setMessage("获取机构列表");
                }
            } catch (Exception e) {
                e.printStackTrace();
                baseResponse.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
                baseResponse.setCode(Constants.ERR_CODE);
            }
            return baseResponse;
        }

    }

}